package com.tiance.demo.service.mysql;

import com.tiance.demo.service.mysql.analyzer.PageAnalyzer;
import com.tiance.demo.service.mysql.bo.Page;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class IBDataReaderMain {

    //    private static String fileName = "D:\\develop\\mysql\\mysql-5.7.24-winx64\\data\\dadaabc\\person_info.ibd";
//    private static String fileName = "/home/alex/account.ibd";
    private static String fileName = "/data/data0/student_class_hour_compensation_snapshot.ibd";

    public static void main(String[] args) {
        File file = new File(fileName);
        byte[] ibdBytes = new byte[(int) file.length()];
        try (FileInputStream fis = new FileInputStream(fileName)) {
            fis.read(ibdBytes);
            List<byte[]> pageBytes = splitIntoPage(ibdBytes);

            List<Page> pages = analysePage(pageBytes);

            List<Page> undoPages = pages.stream().filter(p -> p.getFileHeader().getType().equals("00 02")).collect(Collectors.toList());
            for (Page page : undoPages) {
                System.out.println("");
                System.out.println(page.getFileHeader().getType());
                System.out.println(page);
            }
            System.out.println(pages.get(3));
            System.out.println(pages.get(4));


            //TODO 展现
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<byte[]> splitIntoPage(byte[] bytes) {
        List<byte[]> list = new ArrayList<>();

        int offset = 0;
        while (bytes.length > offset) {
            byte[] pageBytes = new byte[Page.SIZE];
            System.arraycopy(bytes, offset, pageBytes, 0, Page.SIZE);
            offset = offset + Page.SIZE;
            list.add(pageBytes);
        }

        return list;
    }

    private static List<Page> analysePage(List<byte[]> pageBytes) {
        List<Page> pages = new ArrayList<>(pageBytes.size());
        for (byte[] pageByte : pageBytes) {
            Page page = PageAnalyzer.analyse(pageByte);
            pages.add(page);
        }

        return pages;
    }
}
